# -*- coding: utf-8 -*-
# @Time    : 2020/9/27 18:06
# @Author  : Mr. Cui
# @File    : gen_qr.py
# @Software: PyCharm
import json
import os
import shutil
import socket
import time

import qrcode
import requests
from PIL import Image

from application.apps.d_bot.service.get_package_path import *

# QR_DIR='application/apps/d_bot/static/'

QR_DIR = Config.QR_DIR
STATIC_SERVICE=Config.STATIC_SERVICE


def make_qr(url, icon, img_path):
    qr = qrcode.QRCode(
        version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=8, border=4)
    qr.add_data(url)
    qr.make(fit=True)

    img = qr.make_image()
    img = img.convert("RGBA")

    icon = Image.open(QR_DIR + "icon/%s.jpg" % icon)  # 这里是二维码中心的图片

    img_w, img_h = img.size
    factor = 4
    size_w = int(img_w / factor)
    size_h = int(img_h / factor)

    icon_w, icon_h = icon.size
    if icon_w > size_w:
        icon_w = size_w
    if icon_h > size_h:
        icon_h = size_h
    icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

    w = int((img_w - icon_w) / 2)
    h = int((img_h - icon_h) / 2)
    icon = icon.convert("RGBA")
    img.paste(icon, (w, h), icon)
    img.save(img_path)  # 显示图片,可以通过save保存
    return img


def get_host_ip():
    """
    查询本机ip地址
    :return:
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip


def gen_anr_img(path):
    ts = str(int(time.time() * 1000))
    filepath = QR_DIR + 'download/' + ts + '.' + path.split('.')[-1]
    shutil.copy(path, filepath)
    # img = qrcode.make("http://{}:5000/".format(get_host_ip()) + filepath)
    img_path = QR_DIR + 'img/' + ts + '.gif'
    # img.save(img_path)
    make_qr("http://{}/".format(STATIC_SERVICE) + "/".join(filepath.split("/")[-2:]), "android", img_path)
    return str(img_path)


def gen_ios_img(path):
    ts = str(int(time.time() * 1000))
    filepath = QR_DIR + 'download/' + ts + '.' + path.split('.')[-1]
    shutil.copy(path, filepath)
    ip = get_host_ip()
    plist_url = requests.get(
        "https://360che.b7.cm/plist?app_url=http://%s/download/%s.ipa" % (STATIC_SERVICE, ts)).text
    url = 'itms-services://?action=download-manifest&url=%s' % plist_url
    # url = 'itms-services://?action=download-manifest&url=https://{}:5051/download/{}.plist'.format(ip, ts)
    # img = qrcode.make(url)
    img_path = QR_DIR + 'img/' + ts + '.gif'
    # img.save(img_path)

    make_qr(url, "ios", img_path)

    return str(img_path)


def gen_qrcode(app_path):

    if not os.path.exists(QR_DIR+'download'):
        os.mkdir(QR_DIR+'download')
    if not os.path.exists(QR_DIR+'img'):
        os.mkdir(QR_DIR+'img')
    if not os.path.exists(QR_DIR+'icon'):
        os.mkdir(QR_DIR+'icon')
    if not os.path.exists(QR_DIR+'ftp_dir'):
        os.mkdir(QR_DIR+'ftp_dir')

    # app_path = QR_DIR + "ftp_dir/111.ipa"

    if app_path[-3:] == 'ipa':
        img = gen_ios_img(app_path)
        type = "iOS"
    else:
        img = gen_anr_img(app_path)
        type = "Android"
    # img_path = "http://{}:5000/".format(get_host_ip()) + "/".join(img.split("/")[-4:])
    ret = qiniu(img)
    return ret["data"]["imgPath"], type


# def get_d_token():
#     key="dingmt2nviivjolo710s"
#     appsecret="3danyC-RgXGgQVDahojVNSocY5p6bGvYsjT7su_iTdN7kpQeJfHa9VN9nRmxk1OL"
#     url="https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s"%(key,appsecret)
#     ret=requests.get(url)
#     return ret.json()["access_token"]
#
# def get_d_tel():
#     access_token=get_d_token()
#     url="https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list?access_token=%s"%access_token
#     data={"userid_list":"$:LWCP_v1:$R2coTHP9DTT/7WZgBcPVjA==",
#           "field_filter_list":"sys00-mobile"
#           }
#     ret=requests.post(url,data=data)
#
#     return ret.json()

def send_d_qr(ding_token, name, type, img_url, file_name):
    # img_url,type = gen_qrcode(11)
    # ding_token = 'https://oapi.dingtalk.com/robot/sendBySession?session=7d8dda544ed93514d00035bb2eb78d47'
    # type = "TESTiOS",
    img_url = " ### hi %s，您要的%s安装包已打包完成\n文件名：%s\n ![](%s)" % (name,type,file_name.split("/")[-1],img_url)

    headers = {"Content-Type": "application/json ;charset=utf-8 "}
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": "hi %s，您要的%s安装包已打包，请扫码安装" % (name, type),
            "text": img_url
        },
        "at": {
            "atMobiles": [
            ],
            "isAtAll": False
        },
    }
    ret = requests.post(ding_token, data=json.dumps(data), headers=headers)

    return ret.json()


def send_d_qr_err(ding_token, text):
    HEADERS = {"Content-Type": "application/json ;charset=utf-8 "}
    data = {"msgtype": "text", "text": {"content": "系统错误，" + text}, "at": {"atMobiles": [], "isAtAll": "false"}}
    data = json.dumps(data)
    res = requests.post(ding_token, data=data, headers=HEADERS)

    return res.json()


def qiniu(img):
    # img=FILE_DIR+'img/1601204734448.gif'
    files = {'img': ('1.png', open(img, 'rb'), 'image/png')}
    upload_res = requests.post("https://yz-api.360che.com/image_upload", files=files)
    return upload_res.json()


def main(ding_token, name, text):
    try:
        ftp = MyFtp('192.168.2.250')
        ftp.encoding = "utf-8"
        ftp.login('dev-app', '360che.com')
        files = ftp.run(text.replace(" ",""))
        if files == []:
            send_d_qr_err(ding_token, "暂未找到您想要的安装包")
        else:
            for i in files:
                img_url, type = gen_qrcode(i)
                # file_name=str(i).split("\\")[-1]
                send_d_qr(ding_token, name, type, img_url, i)
        return True
    except Exception as e:
        # print(e)
        send_d_qr_err(ding_token,str(e))
        return False


if __name__ == '__main__':
    ding_token="https://oapi.dingtalk.com/robot/sendBySession?session=0465ccb69bd1f23c934842d38b07d458"
    name="崔金月"
    text="724"
    main(ding_token,name,text)
